import 'package:dio/dio.dart';
import 'package:enjoy_plus_flutter_7/utils/toast.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:permission_handler/permission_handler.dart';

class LocationList extends StatefulWidget {
  const LocationList({super.key});

  @override
  State<LocationList> createState() => _LocationListState();
}

class _LocationListState extends State<LocationList> {
  String _address = '加载中';
  List list = [];
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    if (kIsWeb) {
      _getLocation();
    } else {
// 向用户要位置的授权
      _requestLocationPermission();
    }
  }

  _requestLocationPermission() async {
    // 网页 运行在 浏览器   => 网页的权限来自浏览器
    // 浏览器 运行在 系统中  =>  浏览器的权限来自系统(需要检查你们的系统有没有禁用 浏览器的位置权限)
    PermissionStatus status = await Permission.location
        .request(); // 请求位置权限  requestPermissionFromUser+module.json5中配权限
    if (status == PermissionStatus.granted) {
      print('获取位置权限成功');
      // 获取当前位置的经纬度 封装一个函数
      _getLocation();
    } else {
      print('获取位置权限失败');
    }
  }

  _getLocation() async {
    Position p = await Geolocator.getCurrentPosition();
    print('${p.longitude} ${p.latitude}');
    // 经纬度转出具体的位置呢?? 三方库(高德)   鸿蒙全是内置的模块

    // 封装函数 逆地理编码
    _getAddress(p.longitude, p.latitude);
    _searchAround(p.longitude, p.latitude);
  }

  _getAddress(double longitude, double latitude) async {
    Dio dio = Dio();
    var res = await dio
        .get('https://restapi.amap.com/v3/geocode/regeo', queryParameters: {
      'key': 'b15bf4914b2074987754428eb12b8d8d',
      'location': '$longitude,$latitude',
    });
    print(res);
    if (res.data['infocode'] == '10000') {
      setState(() {
        _address = res.data['regeocode']['formatted_address'];
      });
    } else {
      // print('逆地理编码失败');
      PromptAction.error('逆地理编码失败');
    }
  }

  //周边搜索
  _searchAround(double longitude, double latitude) async {
    Dio dio = Dio();
    var res = await dio
        .get('https://restapi.amap.com/v3/place/around', queryParameters: {
      'key': 'b15bf4914b2074987754428eb12b8d8d',
      'location': '$longitude,$latitude',
      "keywords": "小区",
      "radius": 10000, // 搜索半径
      "offset": 10 // 就查10条
    });
    // print(res.data["pois"]);
    if (res.data['infocode'] == '10000') {
      setState(() {
        list = res.data["pois"];
      });
    } else {
      // print('逆地理编码失败');
      PromptAction.error('获取周边小区失败');
    }
  }

  List<Widget> getListView() {
    return list.map((item) {
      // print(item['name']);
      return Container(
          color: Colors.white,
          padding: const EdgeInsets.all(10),
          child: GestureDetector(
            onTap: () {
              Navigator.pushNamed(context, 'building_list',
                  arguments: {'point': item['name']});
            },
            child: Row(
              children: [
                Expanded(child: Text(item['name'])),
                Row(
                  children: [
                    Icon(Icons.arrow_forward_ios,
                        size: 16, color: Colors.black),
                  ],
                )
              ],
            ),
          ));
    }).toList();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('选择社区'),
      ),
      body: ListView(
        padding: const EdgeInsets.all(10),
        children: [
          const Row(
            children: [
              Text(
                '当前地址',
                style: TextStyle(color: Colors.grey),
              )
            ],
          ),
          const SizedBox(height: 10),
          Container(
            color: Colors.white,
            padding: const EdgeInsets.all(10),
            child: Row(
              children: [
                Expanded(child: Text(_address)),
                Row(
                  children: [
                    Icon(Icons.location_searching_outlined, color: Colors.blue),
                    SizedBox(width: 2),
                    GestureDetector(
                      onTap: () {
                        _getAddress(116.39747, 39.908822999999984);
                        _searchAround(116.39747, 39.908822999999984);
                      },
                      child: Text(
                        '重新定位',
                        style: TextStyle(color: Colors.blue),
                      ),
                    ),
                  ],
                )
              ],
            ),
          ),
          const SizedBox(height: 10),
          const Row(
            children: [
              Text(
                '附近社区',
                style: TextStyle(color: Colors.grey),
              )
            ],
          ),
          const SizedBox(height: 10),
          ListView(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            children: getListView(),
          )
        ],
      ),
    );
  }
}
